#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <err.h>

#include "tfs_conf.h"

static struct TFS_POOL *pool_list = NULL;
static struct TFS_POOL *pool = NULL;

#ifdef TESTING
    int
main (int argc, char *argv[])
{
    struct TFS_POOL *pl = NULL;

    yyparse();

    pl = pool_list;
    for ( ; pl; pl = pl->next) {
        (void)fprintf(stdout, "----");
        if (pl->pool)
            (void)fprintf(stdout, "pool = %s\n", pl->pool);

        if (pl->proc)
            (void)fprintf(stdout, "process = %s\n", pl->proc);

        if (pl->uid)
            (void)fprintf(stdout, "udi = %d\n", pl->uid);

        if (pl->gid)
            (void)fprintf(stdout, "gid = %d\n", pl->gid);

        if (pl->wlimit)
            (void)fprintf(stdout, "wlimit = %u\n", (u_int32_t)pl->wlimit);

        if (pl->rlimit)
            (void)fprintf(stdout, "rlimit = %u\n", (u_int32_t)pl->rlimit);
    }

    return (0);
}
#else

FILE *yyin;
#define DEFAULT_CONFIG "tfs.conf"

int yyparse(void);
int yyrestart(FILE *);

struct TFS_POOL *
tfs_conf(char * file)
{
    if (file == NULL)
        file = DEFAULT_CONFIG;

    if ( (yyin = fopen(file, "r")) == NULL)
        err(EXIT_FAILURE, "cannot open configuration file: %s", file);

    yyrestart(yyin);

    if (yyparse() != 0)
        errx(EXIT_FAILURE, "failure reading configuration file.");

    return (pool_list);
}
#endif /* TESTING */

    int
tfs_pool_alloc(void)
{
    if ( (pool = (struct TFS_POOL *)calloc(1, sizeof(struct TFS_POOL))) == NULL)
        err(EXIT_FAILURE, "pool_init");

    pool->next = pool_list;
    return (0);
}

    int
tfs_pool_set(char *key, char *val, int type)
{
    switch (type) {
        case T_NUM:
            if (strcmp("rlimit", key) == 0)
                pool->op[TFS_READ].limit = (size_t)atoi(val);
            else if (strcmp("wlimit", key) == 0)
                pool->op[TFS_WRITE].limit = (size_t)atoi(val);
            else if (strcmp("user", key) == 0)
                pool->uid = (uid_t)atoi(val);
            else if (strcmp("group", key) == 0)
                pool->gid = (gid_t)atoi(val);
            else
                errx(EXIT_FAILURE, "Number cannot be used with '%s' (value = %s)\n", key, val);

            break;

        case T_WORD:
            if (strcmp("process", key) == 0)
                pool->proc = strdup(val);
            else if (strcmp("pool", key) == 0)
                pool->pool = strdup(val);
            else
                errx(EXIT_FAILURE, "Word  cannot be used with '%s' (value = %s)\n", key, val);

            break;

        default:
            errx(EXIT_FAILURE, "unknown type: %d\n", type);
    }

    return (0);
}

int
tfs_pool_finish(void)
{
    pool_list = pool;
    pool = NULL;
    return (0);
}

